package com.bing.jh.service.impl;

import com.bing.jh.entity.HivestatOverViewEntity;
import com.bing.jh.mapper.HivestatDao;
import com.bing.jh.service.HivestatService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("hivestatService")
public class HivestatServiceImpl implements HivestatService {
    @Resource
    private HivestatDao hivestatDao;

    private List<HivestatOverViewEntity> fiveOrderType(String externalSystem, String dataTime, String endTime, String province) {
        List<HivestatOverViewEntity> list = new ArrayList<>();
        List<HivestatOverViewEntity> zdBaseCountList = hivestatDao.getSummaryCountList(externalSystem, Arrays.asList("拆机工单明细", "装机工单明细", "低满工单数据", "投诉工单明细", "移机工单明细"), dataTime, endTime, province, true);
        Map<String, List<HivestatOverViewEntity>> collect = zdBaseCountList.stream().collect(Collectors.groupingBy(HivestatOverViewEntity::getProvince));
        collect.forEach((provinceName, zdList) -> {
            HivestatOverViewEntity nationalEntity = new HivestatOverViewEntity();
            if (Objects.nonNull(zdList.get(0).getCount())) {
                final long count = zdList.stream().mapToLong(HivestatOverViewEntity::getCount).sum();
                final long validNum = zdList.stream().mapToLong(HivestatOverViewEntity::getValidNum).sum();
                final long errorNum = zdList.stream().mapToLong(HivestatOverViewEntity::getErrorNum).sum();
                final long emptyNum = zdList.stream().mapToLong(HivestatOverViewEntity::getEmptyNum).sum();
                DecimalFormat df = new DecimalFormat("#.####");
                nationalEntity.setCount(count);
                nationalEntity.setValidNum(validNum);
                nationalEntity.setErrorNum(errorNum);
                nationalEntity.setEmptyNum(emptyNum);
                getSum(validNum, errorNum, emptyNum, nationalEntity, df);
            }
            nationalEntity.setProvince(provinceName);
            nationalEntity.setExternalSystem(externalSystem);
            nationalEntity.setDataModel("五类工单汇总");
            list.add(nationalEntity);
        });
        return list;
    }

    @Override
    public List<HivestatOverViewEntity> getSummaryCountList(String externalSystem, List<String> dataModel, String dataTime, String endTime, String province) {
        boolean containsDemolitionDetail = dataModel.contains("拆机工单明细");
        List<HivestatOverViewEntity> summaryCountList = hivestatDao.getSummaryCountList(externalSystem, dataModel, dataTime, endTime, province, containsDemolitionDetail);
        if (StringUtils.isEmpty(province)) {
            List<HivestatOverViewEntity> summaryNationalCount = hivestatDao.getSummaryNationalCount(externalSystem, dataModel, dataTime, endTime);
            summaryCountList.addAll(summaryNationalCount);
        }
        if (dataModel.contains("五类工单汇总")) {
            summaryCountList.addAll(fiveOrderType(externalSystem, dataTime, endTime, province));
            summaryCountList.add(getNationalSummaryEntity(externalSystem, dataTime, endTime));
        }
        String s = dataModel.get(0);
        summaryCountList.stream()
                .filter(entity -> !StringUtils.isNotEmpty(entity.getExternalSystem()))
                .forEach(entity -> {
                    entity.setDataModel(s);
                    entity.setExternalSystem(externalSystem);
                });
        return summaryCountList;
    }


    @Override
    public List<Map<String, Object>> queryDataList(String tag, String externalSystem, String dataModel, String dataTime, String province) {
        return null;
    }

    private HivestatOverViewEntity getNationalSummaryEntity(String externalSystem, String dataTime, String endTime) {
        List<HivestatOverViewEntity> nationalCountList = hivestatDao.getSummaryNationalCount(externalSystem, Arrays.asList("拆机工单明细", "装机工单明细", "低满工单数据", "投诉工单明细", "移机工单明细"), dataTime, endTime);
        long count = 0;
        long validNum = 0;
        long errorNum = 0;
        long emptyNum = 0;
        for (HivestatOverViewEntity entity : nationalCountList) {
            count += entity.getCount();
            validNum += entity.getValidNum();
            errorNum += entity.getErrorNum();
            emptyNum += entity.getEmptyNum();
        }
        HivestatOverViewEntity nationalEntity = new HivestatOverViewEntity();
        DecimalFormat df = new DecimalFormat("#.####");
        nationalEntity.setProvince("全国");
        nationalEntity.setExternalSystem(externalSystem);
        nationalEntity.setDataModel("五类工单汇总");
        nationalEntity.setCount(count);
        nationalEntity.setValidNum(validNum);
        nationalEntity.setErrorNum(errorNum);
        nationalEntity.setEmptyNum(emptyNum);
        getSum(validNum, errorNum, emptyNum, nationalEntity, df);
        return nationalEntity;
    }

    /**
     * 统计概览-基础统计
     *
     * @param externalSystem
     * @param dataModel
     * @param dataTime
     * @return
     */
    @Override
    public List<HivestatOverViewEntity> getBaseCountList(String externalSystem, List<String> dataModel, String dataTime, String province) {
        boolean containsDemolitionDetail = dataModel.contains("拆机工单明细");
        List<HivestatOverViewEntity> baseCountList = hivestatDao.getBaseCountList(externalSystem, dataModel, dataTime, province, containsDemolitionDetail);
        if (dataModel.contains("综调数据汇总")) {
            baseCountList.addAll(getZdCountListEntity(externalSystem, dataTime, province));
            baseCountList.add(getBaseCountListEntity(externalSystem, dataTime));
        }
        if (StringUtils.isEmpty(province)) {
            //province为空，不省公司的时候，需要加上全国的记录
            List<HivestatOverViewEntity> nationalCount = hivestatDao.getNationalCount(externalSystem, dataModel, dataTime);
            baseCountList.addAll(nationalCount);
        }

        String s = dataModel.get(0);
        baseCountList.stream()
                .filter(entity -> !StringUtils.isNotEmpty(entity.getExternalSystem()))
                .forEach(entity -> {
                    entity.setDataModel(s);
                    entity.setExternalSystem(externalSystem);
                });

        return baseCountList;
    }

    private List<HivestatOverViewEntity> getZdCountListEntity(String externalSystem, String dataTime, String province) {
        List<HivestatOverViewEntity> list = new ArrayList<>();
        List<HivestatOverViewEntity> zdBaseCountList = hivestatDao.getBaseCountList(externalSystem, Arrays.asList("综调平台人员基础信息", "质检抽检工单", "资源修复工单", "综调支撑工单"), dataTime, province, false);
        Map<String, List<HivestatOverViewEntity>> collect = zdBaseCountList.stream().collect(Collectors.groupingBy(HivestatOverViewEntity::getProvince));
        collect.forEach((provinceName, zdList) -> {
            HivestatOverViewEntity nationalEntity = new HivestatOverViewEntity();
            if (Objects.nonNull(zdList.get(0).getCount())) {
                final long count = zdList.stream().mapToLong(HivestatOverViewEntity::getCount).sum();
                final long validNum = zdList.stream().mapToLong(HivestatOverViewEntity::getValidNum).sum();
                final long errorNum = zdList.stream().mapToLong(HivestatOverViewEntity::getErrorNum).sum();
                final long emptyNum = zdList.stream().mapToLong(HivestatOverViewEntity::getEmptyNum).sum();
                DecimalFormat df = new DecimalFormat("#.####");
                nationalEntity.setCount(count);
                nationalEntity.setValidNum(validNum);
                nationalEntity.setErrorNum(errorNum);
                nationalEntity.setEmptyNum(emptyNum);
                getSum(validNum, errorNum, emptyNum, nationalEntity, df);
            }
            nationalEntity.setProvince(provinceName);
            nationalEntity.setExternalSystem(externalSystem);
            nationalEntity.setDataModel("综调数据汇总");
            list.add(nationalEntity);
        });
        return list;
    }

    private void getSum(long validNum, long errorNum, long emptyNum, HivestatOverViewEntity nationalEntity, DecimalFormat df) {
        nationalEntity.setValidRate(Double.valueOf(df.format((double) validNum / (validNum + emptyNum + errorNum))));
        nationalEntity.setEmptyRate(Double.valueOf(df.format((double) emptyNum / (validNum + emptyNum + errorNum))));
        nationalEntity.setErrorRate(Double.valueOf(df.format((double) errorNum / (validNum + emptyNum + errorNum))));
    }

    private HivestatOverViewEntity getBaseCountListEntity(String externalSystem, String dataTime) {
        List<HivestatOverViewEntity> nationalCount = hivestatDao.getNationalCount(externalSystem, Arrays.asList("综调平台人员基础信息", "质检抽检工单", "资源修复工单", "综调支撑工单"), dataTime);
        long count = 0;
        long validNum = 0;
        long errorNum = 0;
        long emptyNum = 0;
        for (HivestatOverViewEntity entity : nationalCount) {
            count += entity.getCount();
            validNum += entity.getValidNum();
            errorNum += entity.getErrorNum();
            emptyNum += entity.getEmptyNum();
        }
        HivestatOverViewEntity nationalEntity = new HivestatOverViewEntity();
        DecimalFormat df = new DecimalFormat("#.####");
        nationalEntity.setProvince("全国");
        nationalEntity.setExternalSystem(externalSystem);
        nationalEntity.setDataModel("综调数据汇总");
        nationalEntity.setCount(count);
        nationalEntity.setValidNum(validNum);
        nationalEntity.setErrorNum(errorNum);
        nationalEntity.setEmptyNum(emptyNum);
        getSum(validNum, errorNum, emptyNum, nationalEntity, df);
        return nationalEntity;
    }


    private List<String> getBetweenMonths(String startTime, String endTime) {
        List<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date start = sdf.parse(startTime);
            Date end = sdf.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            // 加了一个月
            tempStart.add(Calendar.MONTH, 1);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            result.add(sdf.format(start));
            tempEnd.add(Calendar.MONTH, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                result.add(sdf.format(tempStart.getTime()));
                tempStart.add(Calendar.MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static List<String> getBetweenDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }
}
